<?php 
class CIntroductionContest
{
	static function get_info()
	{
		return CDataXmlStore('data/'.CPortal::$default.'/introduction_contest.xml')->select('contest');
	}
	static function get_start_week_date($time = 0)
	{
		if(!$time)
		{
			$time = time();
		}
		else
		{
			$time = CDateTime($time)->time;
		}
		$time = strtotime(date('m/d/Y',$time));
		return $time-(date('w', $time)?(date('w', $time)-1):6)*24*3600;
	}
	static function get_level($user_id, $week_date)
	{
		$all_users = CTable('referencer_report')->select_all(array('week_date'=>$week_date,), array('order_by'=>'week_total DESC'));
		$week_level = 0;
		foreach($all_users as $user)
		{
			$week_level++;
			if($user['user_id'] == $user_id)
			{
				return $week_level;
			}
		}
		return 0;
	}
	static function get_top_users($limit)
	{
		return CTable('referencer_report')->select_all(array('week_date'=>CIntroductionContest::get_start_week_date(),), array('order_by'=>'week_total DESC', 'items_per_page'=>$limit));
	}
	static function increment_total($id)
	{
		if($user = CTable('user')->select($id))
		{
			CTable('user')->update(array('total_introduction'=>$user['total_introduction']+1,), $id);
			$week_date = CIntroductionContest::get_start_week_date();
			if($week = CTable('referencer_report')->select(array(
				'week_date'=>$week_date,
				'user_id'=>$id
			)))
			{
				CTable('referencer_report')->update(array(
					'week_total'=>$week['week_total']+1,
				), $week['id']);
			}
			else
			{
				CTable('referencer_report')->insert(array(
					'week_total'=>1,
					'week_date'=>$week_date,
					'user_id'=>$id,
					'email'=>$user['id'],
					'full_name'=>$user['full_name'],
					'start_time'=>time(),
				));
			}
			$date = strtotime(date('m/d/Y',time()));
			if($day = CTable('referencer_daily_report')->select(array(
				'date'=>$date,
				'user_id'=>$id
			)))
			{
				CTable('referencer_daily_report')->update(array(
					'day_total'=>$day['day_total']+1,
				), $day['id']);
			}
			else
			{
				CTable('referencer_daily_report')->insert(array(
					'day_total'=>1,
					'date'=>$date,
					'user_id'=>$id,
					'email'=>$user['id'],
					'full_name'=>$user['full_name'],
					'start_time'=>time(),
				));
			}
		}
	}
}
